
package com.platform.server.service.impl;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.platform.server.common.Constant;
import com.platform.server.dao.MessageDao;
import com.platform.server.dao.PayOrderDao;
import com.platform.server.dao.ServerDao;
import com.platform.server.dao.UserDao;
import com.platform.server.dao.WalletDao;
import com.platform.server.entity.Order;
import com.platform.server.entity.Withdraw;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.service.WalletService;
import com.platform.server.util.AuroraPush;
import com.platform.server.util.CfbpayDemoUtils;
import com.platform.server.util.CfbpayDemoUtils2;
import com.platform.server.util.CfbpayDemoUtils4;
import com.platform.server.util.StringTools;
import com.platform.server.util.WxpayDemoUtils;
import com.platform.server.util.WxpayDemoUtils2;
import com.platform.server.util.WxpayDemoUtils4;
import com.szrca.ima.utils.MD5Util;

@Service
public class WalletServiceImpl implements WalletService {

	@Autowired
	private WalletDao walletDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private PayOrderDao payOrderDao;

	@Autowired
	private ServerDao serverDao;

	@Autowired
	private MessageDao messageDao;

	/**
	 * 我的余额
	 */
	@Override
	public ReturnData selectMywallet(String id) {
		if (StringTools.isEmpty(id)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = walletDao.selectMywallet(id);
		if (map == null) {
			return new ReturnData(100, "未找到该用户信息");
		}
		return new ReturnData(map, 200, "成功");
	}

	/**
	 * 充值金额列表
	 */
	@Override
	public ReturnData selectMoneyList() {
		Map<String, Object> map = new HashMap<>();
		// 查看活动优惠券列表
		List<Map<String, Object>> selectDiscount = walletDao.selectDiscount();
		if (selectDiscount.size() == 1) {
			if (selectDiscount.get(0).get("id").toString().equals("2")) {
				List<Map<String, Object>> lists = walletDao.selectActivityList();
				if (lists.size() > 0) {
					map.put("type", "活动");
					map.put("lists", lists);
					return new ReturnData(map, 200, "成功");
				}
			}
		}
		// 查看普通优惠券列表
		List<Map<String, Object>> arrayList = walletDao.selectCommonList();
		map.put("type", "普通");
		map.put("lists", arrayList);
		return new ReturnData(map, 200, "成功");
	}

	/**
	 * 微信或支付宝充值
	 */
	@Override
	public ReturnData topUpRecharge(String userid, String payMethod, String body, String subject, String payMoney,
			String type, String discountid, String ip) throws Exception {
		ReturnData ReturnData = new ReturnData();
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(payMethod) || StringTools.isEmpty(body)
				|| StringTools.isEmpty(subject) || StringTools.isEmpty(payMoney) || StringTools.isEmpty(type)
				|| StringTools.isEmpty(discountid)) {
			return new ReturnData(12, "参数有误");
		}
		String orderid = WxpayDemoUtils.getRandomString(16);
		if ("1".equals(payMethod)) {
			ReturnData = WxpayDemoUtils2.wxPay(body, orderid, payMoney, ip, type + "," + discountid + "," + userid);
		} else if ("2".equals(payMethod)) {
			ReturnData = CfbpayDemoUtils2.returnAlipayPayParam(body, subject, orderid, payMoney,
					type + "," + discountid + "," + userid);
		} else {
			return new ReturnData(10, "支付方式有误");
		}
		return ReturnData;
	}

	/**
	 * 设置支付密码
	 */
	@Override
	public ReturnData setPayPassword(String userid, String password, String surePassword) throws Exception {
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(password) || StringTools.isEmpty(surePassword)) {
			return new ReturnData(12, "参数有误");
		}
		if (!password.equals(surePassword)) {
			return new ReturnData(20, "两次密码输入不一致");
		}
		if (password.length() != 6 || !password.matches("^[0-9]{6}$")) {
			return new ReturnData(30, "请输入6位数字密码");
		}
		int flag = walletDao.setPayPassword(userid, MD5Util.getMD5(password));
		
		//throw new Exception("错误");
		if (flag > 0) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 微信或支付宝或钱包支付服务
	 */
	@Override
	public ReturnData payServer(String userid, String payMethod, String body, String subject, String payMoney,
			String ip, String orderid, String password, String discountid, String order_type) throws Exception {
		ReturnData ReturnData = new ReturnData();
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(payMethod) || StringTools.isEmpty(body)
				|| StringTools.isEmpty(subject) || StringTools.isEmpty(payMoney) || StringTools.isEmpty(orderid)
				|| StringTools.isEmpty(order_type)) {
			return new ReturnData(12, "参数有误");
		}
		if (StringTools.isEmpty(discountid)) {
			discountid = "0";
		}
		if ("1".equals(payMethod)) {
			ReturnData = WxpayDemoUtils4.wxPay(body, orderid, payMoney, ip,
					orderid + "," + userid + "," + payMoney + "," + discountid + "," + order_type);
		} else if ("2".equals(payMethod)) {
			ReturnData = CfbpayDemoUtils4.returnAlipayPayParam(body, subject, orderid, payMoney,
					orderid + "," + userid + "," + payMoney + "," + discountid + "," + order_type);
		} else if ("3".equals(payMethod)) {
			Map<String, Object> usermap = serverDao.selectUserMoney(userid);
			List<Map<String, Object>> selectServerOrder = serverDao.selectServerOrder(orderid, order_type);
			if (selectServerOrder.size() > 1) {
				for (int i = selectServerOrder.size() + 1; i < selectServerOrder.size(); i--) {
					if (i == 1) {
						serverDao.deleteOrder(selectServerOrder.get(i).get("id").toString());
					}
				}
			}
			// 查看订单详情
			Order order = payOrderDao.selectOrderInfo(orderid, order_type);
			if (usermap == null) {
				return new ReturnData(15, "未找到该用户信息");
			}
			String pay_password = (String) usermap.get("pay_password"); // 用户钱包密码
			if (StringTools.isEmpty(pay_password)) {
				return new ReturnData(20, "请先设置支付密码");
			}
			String money = usermap.get("money").toString(); // 用户钱包金额
//			if (Double.parseDouble(money) < 29D) {
//				return new ReturnData(30, "钱包金额不足，请先充值");
//			}
			if (!MD5Util.getMD5(password).equals(pay_password)) {
				return new ReturnData(40, "密码错误");
			}
			/**
			 * 增加用户记录
			 */

			Map<String, Object> platform_map = serverDao.selectUserMoney("1");
			String platform_money = platform_map.get("money").toString();
			// System.out.println(Double.valueOf(platform_money)+Double.valueOf(payMoney)+""+"--------111");
			serverDao.insertCancelOrder(userid, payMoney, "预约预付", order.getOrder_id(),
					Double.valueOf(money) - Double.valueOf(payMoney) + "", Constant.EXPEND,
					Double.valueOf(platform_money) + Double.valueOf(payMoney) + "", null);
			// serverDao.insertCancelOrder("1",payMoney,"平台订单收入",orderid,Double.valueOf(platform_money)+Double.valueOf(payMoney)+"",Constant.INCOME);
			serverDao.returnUserMoney("1", Double.valueOf(platform_money) + Double.valueOf(payMoney) + "");
			if (discountid != "0") {
				// 修改优惠券为已使用
				payOrderDao.updateDiscountStatus(Integer.parseInt(discountid));
			}
			Map<String, Object> userhashMap = new HashMap<>();
			userhashMap.put("userid", userid);
			userhashMap.put("money", Double.parseDouble(money) - Double.parseDouble(payMoney));
			int flag1 = serverDao.UpdateUserMoney(userhashMap); // 减少用户钱包金额
			/****************************************************/
			Integer payMoney2 = (int) Double.parseDouble(payMoney.toString()); // 支付金额
			// 修改订单状态为已支付
			int flag = payOrderDao.updateOrderStatus(orderid);
			payOrderDao.updatePayType(orderid, "钱包");
			// 查看积分使用方式
			Map<String, Object> hashMap = userDao.selectIntegeralWay();
			Integer common_vip = Integer.parseInt(hashMap.get("common_vip").toString()); // 普通会员支付一元获得的积分
			Integer copper_vip = Integer.parseInt(hashMap.get("copper_vip").toString()); // 铜牌会员支付一元获得的积分
			Integer silver_vip = Integer.parseInt(hashMap.get("silver_vip").toString()); // 银牌会员支付一元获得的积分
			Integer gold_vip = Integer.parseInt(hashMap.get("gold_vip").toString()); // 金牌会员支付一元获得的积分
			// 用户支付1元，推荐用户获得的积分
			Integer recommend_integral = Integer.parseInt(hashMap.get("recommend_integral").toString());

			// 查看我的积分
			Map<String, Object> map3 = userDao.selectMyIntegral(userid);
			Integer integral3 = Integer.parseInt(map3.get("integral").toString());
			if (order != null) {
				if (!StringTools.isEmpty(order.getIntegral())) {
					if (Double.valueOf(order.getIntegral()) > 0) {
						// 扣除积分
						payOrderDao.updateUserIntegral(userid, integral3 - Double.valueOf(order.getIntegral()) + "");
						// 添加该用户的积分记录
						serverDao.insertIntegralRecord(userid, order.getIntegral(), "积分抵现", null);
					}
				}
			}
			// 查看我的积分
			Map<String, Object> map = userDao.selectMyIntegral(userid);
			Integer endintegral = 0;// 用户最终的积分
			Integer getintegral = 0;// 用户奖励的积分
			Integer integral = Integer.parseInt(map.get("integral").toString());
			if (integral > 100000) {
				System.out.println("金牌会员");
				getintegral = payMoney2 * gold_vip;
				endintegral = payMoney2 * gold_vip + integral;
			} else if (integral > 10000) {
				System.out.println("银牌会员");
				getintegral = payMoney2 * silver_vip;
				endintegral = payMoney2 * silver_vip + integral;
			} else if (integral > 1000) {
				System.out.println("铜牌会员");
				getintegral = payMoney2 * copper_vip;
				endintegral = payMoney2 * copper_vip + integral;
			} else {
				System.out.println("普通会员");
				getintegral = payMoney2 * common_vip;
				endintegral = payMoney2 * common_vip + integral;
			}
			// 修改用户积分
			if (order.getIntegral() != "0") {
				payOrderDao.updateUserIntegral(userid, endintegral.toString());
			} else {
				payOrderDao.updateUserIntegral(userid, endintegral.toString());
			}
			// 添加该用户的积分记录
			serverDao.insertIntegralRecord(userid, getintegral.toString(), "支付奖励", null);

		/*	List<Map<String, Object>> recommendid = payOrderDao.selectRecommendUserInfo(userid);
			if (recommendid.size() > 0 && recommendid != null) {
				for (Map<String, Object> mapre : recommendid) {
					Integer recommend = payMoney2 * recommend_integral; // 推荐用户的奖励积分
					// 查看推荐用户的积分
					Map<String, Object> map2 = userDao.selectMyIntegral(mapre.get("id").toString());
					Integer integral2 = (Integer) map2.get("integral");
					if(integral2!=null){
						Integer endintegral2 = payMoney2 * recommend_integral + integral2;
						// 修改推荐用户积分
						payOrderDao.updateUserIntegral(mapre.get("id").toString(), endintegral2.toString());
						// 添加推荐用户的积分记录
						serverDao.insertIntegralRecord(mapre.get("id").toString(), recommend.toString(), "积分奖励", userid);
					}
				}
			}*/
			// 添加自己的消息
			Map<String, Object> hm = new HashMap<>();
			hm.put("title", "您已预约了一条服务，请注意查看");
			hm.put("type", "1");
			hm.put("recevicer_id", userid);
			hm.put("content", "您已预约了一条服务，请注意查看");
			messageDao.insertMessage(hm);
			// 添加自己的消息
			Map<String, Object> hm2 = new HashMap<>();
			hm2.put("title", "您的服务已被预约，请注意查看");
			hm2.put("type", "1");
			hm2.put("recevicer_id", order.getServer_user_id());
			hm2.put("content", "您的服务已被预约，请注意查看");
			messageDao.insertMessage(hm2);
			if ("2".equals(order_type)) {
				// 修改该需求单号为已完成
				serverDao.demandSure(Integer.parseInt(order.getServer_id()));
				serverDao.updateOrder(order.getServer_id(), "2");
				List<Map<String, Object>> lists = serverDao.selectApplyUserInfo(Integer.parseInt(order.getServer_id()));
				for (int i = 0; i < lists.size(); i++) {
					if (lists.get(i).get("id").toString().equals(order.getServer_user_id())) {
						// 添加自己的消息
						Map<String, Object> hm3 = new HashMap<>();
						hm3.put("title", "您报名的需求已被预约");
						hm3.put("type", "1");
						hm3.put("recevicer_id", lists.get(i).get("id"));
						hm3.put("content", "您报名的需求已被预约");
						messageDao.insertMessage(hm3);
						AuroraPush.pushTargetForDriver(lists.get(i).get("id").toString(), "您报名的需求已被预约");
					} else {
						// 添加自己的消息
						Map<String, Object> hm4 = new HashMap<>();
						hm4.put("title", "报名结束");
						hm4.put("type", "1");
						hm4.put("recevicer_id", lists.get(i).get("id"));
						hm4.put("content", "报名结束");
						messageDao.insertMessage(hm4);
						AuroraPush.pushTargetForDriver(lists.get(i).get("id").toString(), "报名结束");
					}
				}
			} else {
				// 修改该服务单号为已完成
				serverDao.updateServerStatus(Integer.parseInt(order.getServer_id()));
				serverDao.updateOrder(order.getServer_id(), "1");
				AuroraPush.pushTargetForDriver(order.getServer_user_id(), "您的服务已被预约，请注意查看");
			}
			return new ReturnData(200, "支付成功");
		} else {
			return new ReturnData(10, "支付方式有误");
		}
		return ReturnData;
	}

	/**
	 * 判断用户是否有设置支付密码
	 */
	@Override
	public ReturnData judgePayPassword(String userid) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		int flag = walletDao.judgePayPassword(userid);
		return new ReturnData(flag, 200, "成功");
	}

	/**
	 * 提现
	 */
	@Override
	public ReturnData autoWithdraw(Long id,String token) {
		if(!token.equals("HuaTianXiaWithdraw")){
			return new ReturnData(20, "token失败");
		}
		Withdraw selectWithdraw = walletDao.selectWithdraw(id);
		if (selectWithdraw != null) {
			if (selectWithdraw.getState().equals("待审核")) {
				// 提现之前查看用户是否有金额
				String userMoney = userDao.selectUserMoney(selectWithdraw.getUser_id());
				if (Double.parseDouble(userMoney) < Double.parseDouble(selectWithdraw.getMoney())
						|| "0.00".equals(userMoney)) {
					return new ReturnData(20, "用户余额不足");
				}
				String randomString = WxpayDemoUtils.getRandomString(16);
				// 支付宝
				// todo 银行卡
				ReturnData transfer =null;
				
				
				// 提现金额
				Double money = Double.valueOf(selectWithdraw.getMoney());
				// 手续费
				Double service_fee = money*0.008;
				// 实际到账金额
				Double actualMoney = money-service_fee;
				
				// 手续费不大于 1元 扣除一元
				if(service_fee<1){
					actualMoney = money-1;
				}
				if (selectWithdraw.getType().equals("2")) {
					// todo 银行卡
					 transfer = CfbpayDemoUtils.transfer(actualMoney,selectWithdraw.getBank_card(), selectWithdraw.getReal_name(),null,2);
				}
				if (selectWithdraw.getType().equals("1")) {
					// todo 银行卡
					 transfer = CfbpayDemoUtils.transfer(actualMoney,selectWithdraw.getBank_card(), selectWithdraw.getReal_name(),selectWithdraw.getOpen_bank_code(),1);
				}
				if (transfer.getCode() == 200) {
					userDao.updateOrder(transfer.getData()+"", selectWithdraw.getId()+"");
					//userDao.insertMessqge(selectWithdraw.getUser_id(), "你发起的提现已经到账", "3", selectWithdraw.getId()+"");
					return new ReturnData(200,"提现成功");
				} else {
					userDao.updateWithdraw("审核失败", transfer.getMsg()+"", selectWithdraw.getId()+"");
					return new ReturnData(1200,"提现失败");
				}
			}
		}
		return new ReturnData(1200, "提现失败");
	}

	@Override
	public ReturnData checkPayPwd(Integer userId, String payPwd) {
		if(StringTools.isEmpty(payPwd)){
			return new ReturnData(1200,"请先输入支付密码"); 
		 }
           int judgePayPassword = walletDao.judgePayPassword(userId+"");
           if(judgePayPassword==1){
        	   String queryPayPwd = walletDao.queryPayPwd(userId);
        	   if(!StringTools.isEmpty(queryPayPwd)){
        		   String md5 = null;
				try {
					md5 = MD5Util.getMD5(payPwd);
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NullPointerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        		if(!md5.equals(queryPayPwd)){
        			return new ReturnData(1200,"您输入的支付密码错误!"); 
        		}
        		return new ReturnData(200,"验证成功!"); 
        	   }
           }else{
        	   return new ReturnData(1200,"请先设置支付密码"); 
           }
           return new ReturnData(1200,"请先设置支付密码");    
	}

	@Override
	public ReturnData selectStatus() {
		List<Map<String, Object>> selectDiscount = walletDao.selectDiscount();
		for (Map<String, Object> map : selectDiscount) {
			if (map.get("id").toString().equals("3")) {
					return new ReturnData(map, 200, "成功");
			}
		}
		return new ReturnData(100, "成功");
	}
}

